<template>
  <div class="homework-manage">
    <div class="page-header">
      <h2>作业管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        发布新作业
      </el-button>
    </div>

    <el-card class="list-card">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchTitle"
          placeholder="搜索作业标题"
          style="width: 200px;"
          clearable
          @keyup.enter="handleFilter"
        />
        <el-button type="primary" @click="handleFilter">搜索</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="homeworkList"
        style="width: 100%; margin-top: 15px;"
        border
      >
        <el-table-column prop="title" label="作业标题" />
        <el-table-column label="截止时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.deadline) }}
          </template>
        </el-table-column>
        <el-table-column label="附件" width="100">
          <template #default="scope">
            <el-link 
              v-if="scope.row.attachmentUrl" 
              type="primary" 
              @click="handleDownload(scope.row.attachmentUrl)"
            >
              下载
            </el-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="提交情况" width="100">
          <template #default="scope">
            <el-button 
              type="success" 
              size="small" 
              @click="viewSubmissions(scope.row.id)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="editHomework(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 作业表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '发布新作业' : '编辑作业'"
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="homeworkFormRef" 
        :model="homeworkForm" 
        :rules="formRules" 
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="homeworkForm.title" placeholder="请输入作业标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="homeworkForm.content"
            type="textarea"
            rows="5"
            placeholder="请输入作业内容"
          />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker
            v-model="homeworkForm.deadline"
            type="datetime"
            placeholder="选择截止时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :action="null"
            :http-request="handleFileUpload"
            :on-remove="handleFileRemove"
            :limit="1"
            :file-list="fileList"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传附件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                建议上传PDF、Word或者图片文件，大小不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ dialogType === 'create' ? '发布' : '更新' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 作业提交情况对话框 -->
    <el-dialog
      v-model="submissionsDialogVisible"
      title="作业提交情况"
      width="800px"
    >
      <div v-loading="submissionsLoading">
        <el-empty v-if="submissionsList.length === 0" description="暂无学生提交作业" />
        <el-table
          v-else
          :data="submissionsList"
          border
          style="width: 100%"
        >
          <el-table-column prop="studentName" label="学生姓名" width="120" />
          <el-table-column label="提交时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.submitTime) }}
            </template>
          </el-table-column>
          <el-table-column label="附件" width="100">
            <template #default="scope">
              <el-link 
                v-if="scope.row.attachmentUrl" 
                type="primary" 
                @click="handleDownload(scope.row.attachmentUrl)"
              >
                查看
              </el-link>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'info' : 'success'">
                {{ scope.row.status === 0 ? '未批改' : '已批改' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="分数" width="80">
            <template #default="scope">
              {{ scope.row.score !== null ? scope.row.score : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="gradeHomework(scope.row)"
              >
                {{ scope.row.status === 0 ? '批改' : '修改批改' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 批改作业对话框 -->
    <el-dialog
      v-model="gradeDialogVisible"
      title="批改作业"
      width="600px"
    >
      <div v-if="currentSubmission" class="grade-form">
        <div class="submission-info">
          <h3>提交信息</h3>
          <p>学生：{{ currentSubmission.studentName }}</p>
          <p>提交时间：{{ formatDate(currentSubmission.submitTime) }}</p>
          <div class="submission-content">
            <h4>提交内容：</h4>
            <div class="content-box">{{ currentSubmission.content }}</div>
          </div>
          <div v-if="currentSubmission.attachmentUrl" class="submission-attachment">
            <h4>附件：</h4>
            <el-link type="primary" @click="handleDownload(currentSubmission.attachmentUrl)">
              查看附件
            </el-link>
          </div>
        </div>

        <el-divider />

        <div class="grade-section">
          <h3>评分信息</h3>
          <el-form ref="gradeFormRef" :model="gradeForm" :rules="gradeRules" label-width="80px">
            <el-form-item label="分数" prop="score">
              <el-input-number v-model="gradeForm.score" :min="0" :max="100" />
            </el-form-item>
            <el-form-item label="评语" prop="comment">
              <el-input
                v-model="gradeForm.comment"
                type="textarea"
                rows="4"
                placeholder="请输入评语"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="gradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrade" :loading="gradeLoading">
            提交批改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Plus, Upload } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '../../utils/format';
import { useUserStore } from '../../store/user';
import { 
  getTeacherHomeworks, 
  createHomework, 
  updateHomework, 
  deleteHomework, 
  getHomeworkSubmissions,
  gradeHomework as apiGradeHomework 
} from '../../api/homework';
import { uploadHomeworkFile } from '../../api/file';

const router = useRouter();
const userStore = useUserStore();

// 表格数据相关
const loading = ref(false);
const homeworkList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchTitle = ref('');

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref('create'); // create 或 edit
const homeworkFormRef = ref(null);
const submitLoading = ref(false);
const fileList = ref([]);

// 作业表单
const homeworkForm = reactive({
  id: null,
  title: '',
  content: '',
  teacherId: null,
  deadline: '',
  attachmentUrl: ''
});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入作业标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入作业内容', trigger: 'blur' }
  ],
  deadline: [
    { required: true, message: '请选择截止时间', trigger: 'change' }
  ]
};

// 提交情况相关
const submissionsDialogVisible = ref(false);
const submissionsLoading = ref(false);
const submissionsList = ref([]);
const currentHomeworkId = ref(null);

// 批改相关
const gradeDialogVisible = ref(false);
const gradeLoading = ref(false);
const currentSubmission = ref(null);
const gradeFormRef = ref(null);

const gradeForm = reactive({
  submissionId: null,
  score: null,
  comment: ''
});

const gradeRules = {
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '分数范围为0-100', trigger: 'blur' }
  ]
};

// 初始化加载作业列表
onMounted(() => {
  loadHomeworkList();
});

// 加载作业列表
const loadHomeworkList = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const params = {
      teacherId: userStore.userId,
      page: currentPage.value,
      size: pageSize.value
    };
    
    // 添加搜索条件
    if (searchTitle.value) {
      params.title = searchTitle.value.trim();
    }
    
    const response = await getTeacherHomeworks(params);
    
    if (response.code === 200) {
      homeworkList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error('获取作业列表失败');
    }
  } catch (error) {
    console.error('获取作业列表错误:', error);
    ElMessage.error('获取作业列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleFilter = () => {
  currentPage.value = 1;
  loadHomeworkList();
};

// 处理页码大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadHomeworkList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadHomeworkList();
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogType.value = 'create';
  resetForm();
  dialogVisible.value = true;
};

// 取消对话框
const cancelDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 编辑作业
const editHomework = (row) => {
  dialogType.value = 'edit';
  resetForm();
  
  // 设置表单数据
  nextTick(() => {
    homeworkForm.id = row.id;
    homeworkForm.title = row.title;
    homeworkForm.content = row.content;
    homeworkForm.teacherId = row.teacherId;
    homeworkForm.deadline = row.deadline;
    homeworkForm.attachmentUrl = row.attachmentUrl;
    
    // 如果有附件，添加到文件列表
    if (row.attachmentUrl) {
      fileList.value = [{
        name: row.attachmentUrl.split('/').pop() || '附件',
        url: row.attachmentUrl
      }];
    }
    
    dialogVisible.value = true;
  });
};

// 重置表单
const resetForm = () => {
  homeworkForm.id = null;
  homeworkForm.title = '';
  homeworkForm.content = '';
  homeworkForm.teacherId = userStore.userId;
  homeworkForm.deadline = '';
  homeworkForm.attachmentUrl = '';
  fileList.value = [];
  
  // 等表单渲染完成后再重置验证结果
  nextTick(() => {
    if (homeworkFormRef.value) {
      homeworkFormRef.value.resetFields();
    }
  });
};

// 文件上传前校验
const beforeUpload = (file) => {
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过10MB');
    return false;
  }
  return true;
};

// 处理文件上传
const handleFileUpload = async (options) => {
  const { file } = options;
  
  try {
    const response = await uploadHomeworkFile(file);
    if (response.code === 200) {
      homeworkForm.attachmentUrl = response.data;
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败，请稍后重试');
  }
};

// 处理文件移除
const handleFileRemove = () => {
  homeworkForm.attachmentUrl = '';
};

// 提交表单
const submitForm = async () => {
  if (!homeworkFormRef.value) return;
  
  try {
    await homeworkFormRef.value.validate();
  } catch (error) {
    return;
  }
  
  submitLoading.value = true;
  try {
    const submitFn = dialogType.value === 'create' ? createHomework : updateHomework;
    const response = await submitFn(homeworkForm);
    
    if (response.code === 200) {
      ElMessage.success(dialogType.value === 'create' ? '作业发布成功' : '作业更新成功');
      dialogVisible.value = false;
      loadHomeworkList();
    } else {
      ElMessage.error(response.message || '操作失败，请稍后重试');
    }
  } catch (error) {
    console.error('提交作业表单错误:', error);
    ElMessage.error('操作失败，请稍后重试');
  } finally {
    submitLoading.value = false;
  }
};

// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这个作业吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteHomework(id);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        loadHomeworkList();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除作业错误:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

// 查看提交情况
const viewSubmissions = async (homeworkId) => {
  currentHomeworkId.value = homeworkId;
  submissionsLoading.value = true;
  submissionsList.value = [];
  submissionsDialogVisible.value = true;
  
  try {
    const response = await getHomeworkSubmissions(homeworkId);
    if (response.code === 200) {
      submissionsList.value = response.data || [];
    } else {
      ElMessage.error('获取提交情况失败');
    }
  } catch (error) {
    console.error('获取提交情况错误:', error);
    ElMessage.error('获取提交情况失败，请稍后重试');
  } finally {
    submissionsLoading.value = false;
  }
};

// 批改作业
const gradeHomework = (submission) => {
  currentSubmission.value = submission;
  
  // 初始化批改表单
  gradeForm.submissionId = submission.id;
  gradeForm.score = submission.score || 0;
  gradeForm.comment = submission.comment || '';
  
  gradeDialogVisible.value = true;
};

// 提交批改结果
const submitGrade = async () => {
  if (!gradeFormRef.value) return;
  
  try {
    await gradeFormRef.value.validate();
  } catch (error) {
    return;
  }
  
  gradeLoading.value = true;
  try {
    const response = await apiGradeHomework(gradeForm);
    
    if (response.code === 200) {
      ElMessage.success('批改成功');
      gradeDialogVisible.value = false;
      
      // 刷新提交列表
      if (currentHomeworkId.value) {
        viewSubmissions(currentHomeworkId.value);
      }
    } else {
      ElMessage.error(response.message || '批改失败');
    }
  } catch (error) {
    console.error('批改作业错误:', error);
    ElMessage.error('批改失败，请稍后重试');
  } finally {
    gradeLoading.value = false;
  }
};

// 处理附件下载
const handleDownload = (url) => {
  if (!url) return;
  
  // 创建一个隐藏的a标签进行下载
  const link = document.createElement('a');
  link.href = url.startsWith('http') ? url : import.meta.env.VITE_API_BASE_URL + url;
  link.target = '_blank';
  link.download = url.split('/').pop() || '作业附件';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.homework-manage {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.list-card {
  width: 100%;
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-container .el-input {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.submission-info {
  margin-bottom: 20px;
}

.submission-info h3, .grade-section h3 {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.submission-info h4 {
  font-size: 16px;
  margin-top: 10px;
  margin-bottom: 5px;
  color: #606266;
}

.content-box {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  min-height: 80px;
  white-space: pre-wrap;
}

.submission-attachment {
  margin-top: 15px;
}

.el-divider {
  margin: 20px 0;
}
</style> 